gpt4 book ai didi

javascript - Promise then 函数未执行

转载 作者:行者123 更新时间:2023-12-02 15:17:57 24 4
gpt4 key购买 nike

exports.index = function(req, res) {
moviedb.indexMovie().then(function(){
console.log("READ VALUES FROM DATABASE");
});
};

var moviedb = module.exports = {
indexMovie : function() {
return new P(function(resolve, reject){
MovieEntry.removeAsync({})
.then (function() {
return P.map(movieJson, x => movieApi.searchMovies(x.name)).map(x => {
return new MovieEntry({
id: x.id,
title : x.title,
originalTitle : x.originalTitle,
year : x.year,
popularity : x.popularity,
voteAverage : x.voteAverage,
votes : x.votes,
isAdult : x.isAdult,
video : x.video,
poster : x.poster,
backdrop : x.backdrop,
});
}).map(x => x.save())
.then(x => console.log("All Done!"))
.catch(e => { console.error("Error somewhere", e); throw e; });
})
})
}
}

我从来没有看到日志“READ FROM DATABASE”。然而函数indexMovie 执行得很好。我究竟做错了什么。我不太确定这个 promise 是如何发挥作用的。我想确保一旦数据库写入完成,我就可以在 then 调用中从数据库中读取数据。

最佳答案

当您已经有一个可使用的 Promise 时,无需创建新的 Promise。这是一种反模式,此处描述为 deferred antipattern

您应该使用从 removeAsync() 函数给出的 Promise,并让 Promise 链正常执行。

exports.index = function(req, res) {
moviedb.indexMovie().then(function(){
console.log("READ VALUES FROM DATABASE");
});
};

var moviedb = module.exports = {
indexMovie : function() {
return MovieEntry.removeAsync({})
.then (function() {
return P.map(movieJson, x => movieApi.searchMovies(x.name)).map(x => {
return new MovieEntry({
id: x.id,
title : x.title,
originalTitle : x.originalTitle,
year : x.year,
popularity : x.popularity,
voteAverage : x.voteAverage,
votes : x.votes,
isAdult : x.isAdult,
video : x.video,
poster : x.poster,
backdrop : x.backdrop,
});
}).map(x => x.save())
.then(x => {console.log("All Done!"); return; })
.catch(e => { console.error("Error somewhere", e); throw e; });
});
}
}

关于javascript - Promise then 函数未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34312747/

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