gpt4 book ai didi

javascript - promise 不返回 [node.js]

转载 作者:行者123 更新时间:2023-12-03 00:11:00 24 4
gpt4 key购买 nike

我现在正在开发 Dominos Pizza API,当我从主模块 (bot.js) 中 console.log() 时,一切似乎都正常。如果我在测试文件(testnearby.js)中创建一个函数来告诉它console.log(localStore),它不会打印任何内容。代码如下。 /image/ovJMD.png

定义的不起作用的函数(上面提到的)是 getLocalStore

如有任何帮助,我们将不胜感激。代码:

bot.js(主模块):


//START

// TABLE OF THINGS ADDED TO BASKET ETC.

var store = "";
var localStore = null;


// FIND LOCAL STORE

exports.getLocalStore = function(postcode) {
// get the local store
// get the api and find with the postcode provided
// fetch the api
fetch('https://www.dominos.co.uk/storefindermap/storesearch?SearchText=' + postcode)
// json it
.then(res => res.json())
// return it
.then(function(json) {
// return console.log(json.localStore)
// makes it a variable so we can return it elsewhere
localStore = json.localStore
})
return localStore
}
// END


testnearby.js

// START

const ukdomino = require("./bot.js")
const postcode = "L129JH"

ukdomino.getLocalStore(postcode).then(localStore => console.log(localStore))

// END

最佳答案

您需要返回 fetch ...

exports.getLocalStore = function(postcode) {
// get the local store
// get the api and find with the postcode provided
// fetch the api
return fetch('https://www.dominos.co.uk/storefindermap/storesearch?SearchText=' + postcode)
// json it
.then(res => res.json())

}

当您在函数中返回 localStore 时,它​​仍然为 null,因为它在 fetch 设置其值之前返回

关于javascript - promise 不返回 [node.js],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54731839/

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