如何使用 ES6 从 Promise 中 return 多个值?
How to return multiple values from a Promise with ES6?
我有一个函数链。
一路上,我需要跟踪 2 个临时变量。
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
看起来最后一个 return [carto, done]
在具有其中一个值 (done
) 时立即执行。
如果我用 return carto
替换它,它会等待并且 carto 具有正确的 typeof。
但是对于 return [carto, done]
,控制台抛出:
carto: [object Promise]
如何在不使用全局变量的情况下在链中传递多个变量?
编辑:我使用 Svelte,它不想等待异步函数。
你需要使用 Promise.all
,但以一种有点奇怪的方式 - 将之前的 .then
中的 done
传递给它(这不是 Promise,而是普通值),并传递给它新的 carto
, 实际上是 一个 Promise。一旦单数 carto
解析,它将解析为两个值。
})
.then(done => Promise.all([
localforage.getItem("key"),
done,
])
.then(([carto, done]) => {
但请考虑使用 await
,它会使这些事情变得更干净。
setItem
也 returns 一个你应该等待的承诺。
const done = whateverPromiseDoneCameFrom;
await localforage.setItem("key",key);
const carto = await localforage.getItem("key");
我有一个函数链。 一路上,我需要跟踪 2 个临时变量。
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
看起来最后一个 return [carto, done]
在具有其中一个值 (done
) 时立即执行。
如果我用 return carto
替换它,它会等待并且 carto 具有正确的 typeof。
但是对于 return [carto, done]
,控制台抛出:
carto: [object Promise]
如何在不使用全局变量的情况下在链中传递多个变量?
编辑:我使用 Svelte,它不想等待异步函数。
你需要使用 Promise.all
,但以一种有点奇怪的方式 - 将之前的 .then
中的 done
传递给它(这不是 Promise,而是普通值),并传递给它新的 carto
, 实际上是 一个 Promise。一旦单数 carto
解析,它将解析为两个值。
})
.then(done => Promise.all([
localforage.getItem("key"),
done,
])
.then(([carto, done]) => {
但请考虑使用 await
,它会使这些事情变得更干净。
setItem
也 returns 一个你应该等待的承诺。
const done = whateverPromiseDoneCameFrom;
await localforage.setItem("key",key);
const carto = await localforage.getItem("key");