phm
phm

Reputation: 23

How to return multiple values from a Promise with ES6?

I have a chain of functions. Along the way, I need to track 2 temporary variables.

let key="string"
...
.then(done => {
    localforage.setItem("key",key)
    console.log ("done: "+done) // WORKS
    return done
}).then(done => {
    let carto = localforage.getItem("key")
    return [carto, done]
}).then(([carto, done]) => {
    console.log ("done: "+done) // WORKS
    console.log ("carto: "+carto) // FAILS

It looks like the last return [carto, done] is executed as soon as it has one of the values (done).

If I replace it with return carto it waits and carto has the correct typeof.

But with return [carto, done], the console throws: carto: [object Promise]

How to pass multiple variables in a chain without using globals?

EDIT: I use Svelte and it doesn't want await out of async functions.

Upvotes: 0

Views: 93

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

You'll need to use Promise.all, but in a somewhat odd way - pass into it the done from the prior .then (which is not a Promise, but a plain value), and also pass it the new carto, which actually is a Promise. It'll resolve to both values once the singular carto resolves.

})
.then(done => Promise.all([
  localforage.getItem("key"),
  done,
])
.then(([carto, done]) => {

But consider using await instead, it makes these sorts of things much cleaner.

setItem also returns a Promise that you should wait for.

const done = whateverPromiseDoneCameFrom;
await localforage.setItem("key",key);
const carto = await localforage.getItem("key");

Upvotes: 1

Related Questions