Node.js、Mongodb:如何使用 `promise.then` 设置全局变量?

在代码中有一个promise.then试图被用来设置一个全局变量originalUrl,但是originalUrl没有被改变。任何帮助将不胜感激。


我的应用程序.js:


// create a mongoose model

var urlSchema = new mongoose.Schema({

  original_url: String,

  short_url: String

});

urlSchema.plugin(findOrCreate)

var Url = mongoose.model('Url', urlSchema);


let promise = new Promise(function(resolve, reject) {

  app.post("/api/shorturl/new", (req, res) => {

    // receive an url in the post and return a

    // short id. After that, the short id can be used

    // to go to the original url.

    // Handle the data in the POST request

    // get the hostname from the request

    

    originalUrl = req.body.url;

    // Create an identifier for the url

    shortUrl = md5(originalUrl).toString().slice(-7) 

    

     // test to see if the host is live

    var url = new URL(originalUrl);

    hostname = url.hostname;


    // if host is live

    dns.lookup(hostname, function (err) {

      if (err == undefined){

        // if not found, save the original_url and the 

        // short_url, return

          Url.findOrCreate({ original_url: originalUrl, short_url: shortUrl}, (err, result) => {

          console.log(result)


          res.json({

          original_url: originalUrl,

          short_url: shortUrl

          }); 

        })

      }


      if (err != undefined){

        console.log(">>> error <<<")

        res.json({"error":"host down"});

      }

    });

    resolve(originalUrl)

  });

})

promise.then(

  function(result) { originalUrl = result },

  function(error) { /* handle an error */ }

);


console.log(originalUrl) // undefined


MMTTMM
浏览 91回答 1
1回答

开心每一天1111

传递给的函数中的代码then()在承诺解决之前不会运行。所以不是这个:promise.then(&nbsp; function(result) { originalUrl = result },&nbsp; function(error) { /* handle an error */ });console.log(originalUrl)...你需要做更多这样的事情:promise.then(&nbsp; function(result) { originalUrl = result },&nbsp; function(error) { /* handle an error */ }).then(&nbsp; function() { console.log(originalUrl); });这是一个简单的可运行示例,希望可以让您了解其工作原理:var originalUrl = undefined;var promise = new Promise((resolve, reject) => {&nbsp; setTimeout( function() {&nbsp; &nbsp; resolve("http://example.com");&nbsp; }, 250)&nbsp;});promise.then(&nbsp; function(result) { originalUrl = result },&nbsp; function(error) { /* handle an error */ }).then(&nbsp; function() { console.log('promise resolved: ', originalUrl); });console.log('promise pending: ', originalUrl);结果:promise pending:&nbsp; undefinedpromise resolved:&nbsp; http://example.com
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript