【问题标题】:Array push not working inside promise then [duplicate]数组推送在promise中不起作用然后[重复]
【发布时间】:2021-07-19 05:04:04
【问题描述】:

我看不出我做错了什么......推送不起作用并且什么也不返回

import {nearbyUsers, getLatitude, getLongitude} from './helper'
const users = []
nearbyUsers(session, getLatitude(), getLongitude()).then(res => {
    users.push(res)
console.log(users.lenght) //this works fine
})

console.log(users.lenght) //this prints 0

【问题讨论】:

  • console.log(users.lenght) 不会打印除undefined以外的任何内容
  • 这是length 而不是lenght。无论如何,问题是第二个 console.log 返回 0 因为回调尚未执行。您的代码是异步的。

标签: javascript node.js reactjs next.js


【解决方案1】:

问题在于then 回调是异步发生的,这意味着在 then 回调内部的代码执行与它之外的其余代码之间可能(并且可能会)存在延迟。

如果您想依赖异步函数,请务必阅读有关 async/await 的内容。 await 关键字,当放在异步函数之前时,将暂停程序,直到 promise 被解决。

更多信息请参阅herehere

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2014-01-06
    相关资源
    最近更新 更多