Javascript Promise.All与对象映射-未定义
这一次我创造了一个承诺。所有的电话都是这样的tools.isMember和tools.unsubscribe将返回承诺对象Javascript Promise.All与对象映射-未定义,javascript,promise,Javascript,Promise,这一次我创造了一个承诺。所有的电话都是这样的tools.isMember和tools.unsubscribe将返回承诺对象 tools.isMember(userid) .then(results => { Promise.all( Object.keys(results).map((key, index) => { tools.unsubscribe(results[inde
tools.isMember(userid)
.then(results => {
Promise.all(
Object.keys(results).map((key, index) => {
tools.unsubscribe(results[index], userid)
})
)
})
.then(unsubscribe => { console.log('Unsubscribed Results => ', unsubscribed)})
.catch(err => console.log(err))
控制台打印
取消订阅的结果=>未定义
我尝试将日志记录向上移动一点以进行调试,并将console.log放在tools.unsubscribe所在的位置
tools.isMember(userid)
.then(results => {
Promise.all(
Object.keys(results).map((key, index) => {
tools.unsubscribe(results[index], userid).then(result => { console.log('Result from Tools => " result) }) //Added Logging Here
})
)
})
.then(unsubscribe => { console.log('Unsubscribed Results => ', unsubscribe)})
.catch(err => console.log(err))
现在控制台显示
取消订阅的结果=>未定义
工具的结果=>1
现在我知道promise正在从tools.unsubscribed返回预期结果,但是promise.all应该返回一个包含所有结果的数组吗?它现在显示未定义。
我尝试过很多不同的解决问题的方法,但我是个新手。一直在努力找出Promise出了什么问题
更新@Bergie:增加了工具回报。取消订阅
tools.isMember(userid)
.then(results => {
Promise.all(
Object.keys(results).map((key, index) => {
tools.unsubscribe(results[index], userid).then(result => { return result })
})
).then(result => { return result }) //Tryning to interpret Bergie's answer
})
.then(unsubscribe => { console.log('Unsubscribed Results => ', unsubscribed)})
.catch(err => console.log(err))
控制台打印
取消订阅的结果=>未定义
您需要从映射中返回一个承诺,当前您没有返回任何内容,这相当于未定义,体块周围带有花括号的箭头函数需要显式返回,因此您可以添加它,也可以删除花括号 您也不需要
然后
在映射中,您需要返回unsubscribe()
调用的结果,这本身就是一个承诺
因此,您的代码应该是:
tools.isMember(userid)
.then(results => {
Promise.all(
Object.keys(results).map((key, index) => tools.unsubscribe(results[index], userid))
).then(unsubscribe => { console.log('Unsubscribed Results => ', unsubscribed)}) //unsubscribe is an array
.catch(err => console.log(err))
})
编辑:
then()
是Promise对象的一个方法,所以应该在Promise实例上调用它。有关更多详细信息,请参阅
我在arrow函数体中添加return或删除大括号{and}的意思是
(x, y) => x + y
//is equivalent to
(x, y) => {
return x + y
}
//while
(x, y) => {
x + y
}
//is equivalent to
(x, y) => {
x + y
return
}
您没有从
然后
回调返回Promise.all()
Promise,因此它将使用未定义的
进行解析。您也没有返回取消订阅()
promise从map
回调,所以promise。所有只会看到未定义的s数组。Bergi你能看看我更新的代码吗?这就是你的意思,对吗?但问题是它仍然显示未定义。不。我是说在results=>{Promise.all(…)}
和(key,index)=>{…}
回调中缺少return
语句。哇,真管用!我猜我放的地方错了。有时候,下一个放在哪里会让人困惑。你能告诉我你说的花括号是什么意思吗?