亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

MMTTMM 2023-04-20 16:20:33
在代碼中有一個promise.then試圖被用來設置一個全局變量originalUrl,但是originalUrl沒有被改變。任何幫助將不勝感激。我的應用程序.js:// create a mongoose modelvar 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
查看完整描述

1 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

傳遞給的函數中的代碼then()在承諾解決之前不會運行。所以不是這個:


promise.then(

  function(result) { originalUrl = result },

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

);


console.log(originalUrl)

...你需要做更多這樣的事情:


promise.then(

  function(result) { originalUrl = result },

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

).then(

  function() { console.log(originalUrl); }

);

這是一個簡單的可運行示例,希望可以讓您了解其工作原理:


var originalUrl = undefined;


var promise = new Promise((resolve, reject) => {

  setTimeout( function() {

    resolve("http://example.com");

  }, 250) 

});


promise.then(

  function(result) { originalUrl = result },

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

).then(

  function() { console.log('promise resolved: ', originalUrl); }

);

console.log('promise pending: ', originalUrl);

結果:


promise pending:  undefined

promise resolved:  http://example.com


查看完整回答
反對 回復 2023-04-20
  • 1 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號