Javascript 承诺不返回[node.js]

Javascript 承诺不返回[node.js],javascript,node.js,Javascript,Node.js,我现在正在开发一个多米诺骨牌披萨API,当我从主模块bot.js中运行console.log时,一切似乎都正常。如果我在测试文件testnear.js中创建一个函数,告诉它console.loglocalStore,它不会打印任何内容。代码如下 上面提到的不起作用的函数是getLocalStore 任何帮助都将不胜感激。 代码: bot.js主模块: //START // TABLE OF THINGS ADDED TO BASKET ETC. var store = ""; var l

我现在正在开发一个多米诺骨牌披萨API,当我从主模块bot.js中运行console.log时,一切似乎都正常。如果我在测试文件testnear.js中创建一个函数,告诉它console.loglocalStore,它不会打印任何内容。代码如下

上面提到的不起作用的函数是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
您需要返回取回


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

,并且邮政编码是假的,但在转到实际的API链接时仍然有效。不回传localStore@bambamukdomino.getLocalStorepostcode.then是一个函数。同时更改了UKDOMO.getLocalStorepostcode.thenfetch=>console.LogFetch请显示您的实际代码。它的工作原理与我在回答中描述的一样。请不要回答重复的问题,而是引用重复的问题并相应地标记问题。这可能是最常见的复制品了。@connexo抱歉,我确实看到了那篇文章,但我不理解它。只要我将returnlocalstore移到localStore=json.localStore下面,这个解决方案就可以工作。谢谢。然后你需要完全删除第二个,以及之后的所有内容,就像答案一样@罗斯
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())

}