gpt4 book ai didi

javascript - 在 javascript 中使用 then 范围之外的数据

转载 作者:行者123 更新时间:2023-11-30 11:54:13 25 4
gpt4 key购买 nike

我在 JavaScript 中被赋予了以下任务:使用名为 getData 的方法创建一个 DataBase 对象,该方法返回一个 promise 。当这个 promise 被解决时,它返回一个数组。

创建另一个名为 Data 的对象,该对象调用 getData 方法。为 Data 创建一个名为 getFirst 的方法,它返回数组中第一个成员的值。

如果我理解这个任务,那是不可能的,因为你不能在回调之外从 promise 中分配值。

(实际上,任务更复杂,但我正在简化以仅显示我遇到问题的部分。)

这是我所拥有的:

function DataBase(){
this.getData = function(){
var data = [1, 2, 3, 4, 5];
return Promise.resolve(data);
}
}

function Data(d){
this.first = null;
that = this;
this.getFirst = function(){
return this.first;
}
this.initialize = function(){
dataBase = new DataBase();
dataBase.getData().then( function(theArray){
console.log(theArray); //works fine
that.first = theArray[0]; //doesn't work because promise is asyncronous
})
}
}

d = new Data();
d.initialize();
result = d.getFirst();
console.log(result)// is null

最佳答案

initialize 函数上使用一个 promise,并从 initialze 函数内部返回一个 promise:

this.initialize = function(){
dataBase = new DataBase();
return dataBase.getData().then( function(theArray){
console.log(theArray); //works fine
that.first = theArray[0]; //doesn't work because promise is asyncronous
})
}

d.initialize().then(function() {
result = d.getFirst();
console.log(result);
});

关于javascript - 在 javascript 中使用 then 范围之外的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544131/

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