gpt4 book ai didi

javascript - promise 返回未定义

转载 作者:行者123 更新时间:2023-11-28 14:46:21 25 4
gpt4 key购买 nike

export function getHotOffers() {
let offers;
getRequest('/hot-offers').then(x => offers = x);
alert(offers);
return JSON.parse(offers);
}

这是我导出的函数。它异步向服务器发出请求并获取 JSON 字符串。当我调试项目时,一切正常,警报返回字符串,但是当我执行代码时,警报返回未定义。我该如何解决这个问题?

最佳答案

这不是 Promise 的工作原理。 getRequest() 之后的代码不会等待 Promise 完成 - 它会立即运行。

export function getHotOffers() {
let offers;
getRequest('/hot-offers').then( x =>
//this only happens after the request is done
offers = x
);
//this code runs right away, before the request completes
alert(offers);
//so does this, so "offers" will be undefined at this point
return JSON.parse(offers);
}

请求返回后运行的所有代码都应该在回调中,如下所示:

export function getHotOffers() {
return getRequest('/hot-offers');
}

//somewhere else
getHotOffers().then( offers => {
useTheOffers( offers );
});

关于javascript - promise 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46265565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com