相关疑难解决方法(0)

我可以假设承诺中的错误会冒出新的Promise并抓住它吗?

我有一个函数,如果发现任何东西,它将查找缓存,否则它将继续并获取数据并设置缓存。这是很标准的。我想知道错误是否发生在最内部的函数上,它将使气泡上升到最外部的Promise吗?因此,我只能拥有一个catch而不是一个。

这是我的代码。

我正在使用蓝鸟

 var _self = this;
    return new Promise(function(resolve, reject) {
      _self.get(url, redisClient).then(function getCacheFunc(cacheResponse) {
        if(cacheResponse) {
          return resolve(JSON.parse(cacheResponse));
        }
        webCrawl(url).then(function webCrawl(crawlResults) {
          _self.set(url, JSON.stringify(crawlResults), redisClient);
          return resolve(crawlResults);
        }).catch(function catchFunc(error) {
          return reject(error); // can I delete this catch
        });
      }).catch(function getCacheErrorFunc(cacheError) {
        return reject(cacheError); // and let this catch handle everything?
      });
    });
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise bluebird

5
推荐指数
1
解决办法
2451
查看次数

如何递归调用promise函数

我正在尝试使用 javascript Promise 递归调用异步函数,但尚未找到有效的模式。

这就是我想象的工作:

var doAsyncThing = function(lastId){
  new Promise(function(resolve, reject){
    // async request with lastId
    return resolve(response)
  }
}

var recursivelyDoAsyncThing = function(lastId){
  doAsyncThing(lastId).then(function(response){
    return new Promise(function(resolve, reject){
      //do something with response
      if(response.hasMore){
        //get newlastId
        return resolve(recursivelyDoAsyncThing(newLastId));
      }else{
        resolve();
      }
    });
  });
}

recursivelyDoAsyncThing().then( function(){
  console.log('done');
});
Run Code Online (Sandbox Code Playgroud)

为什么这不起作用?我误解了什么?

有没有更好的模式来解决这个问题?

javascript recursion promise

5
推荐指数
1
解决办法
3340
查看次数

使用promise的异步递归

所以我试图将我的代码转移到"Promise world",并且在很多地方,当我不得不"循环"异步功能时 - 我只是以这种方式使用递归

function doRecursion(idx,callback){
    if(idx < someArray.length){
        doAsync(function(){
            doRecursion(++idx,callback)
        });
    }else{
        callback('done!')
    }
}
doRecursion(0,function(msg){
    //...
});
Run Code Online (Sandbox Code Playgroud)

现在我正试图改变进入Promise世界,我很困惑

var Promise = require('bluebird')
function doRecursion(idx){
    return new Promise(function(resolve){
        if(idx < someArray.length){
            doAsync(function(){
                //... doRecursion(++idx)
                // how do i call doRecusion here....
            });
        }else{
            resolve('done!')
        }
    });
}
doRecursion(0).then(function(msg){
    //...
});
Run Code Online (Sandbox Code Playgroud)

谢谢.

javascript recursion node.js promise

5
推荐指数
1
解决办法
118
查看次数

如何使用 javascript 制作递归抓取器?

所以我正在制作一个用于学习目的的小爬虫,最终我应该得到网站上页面的树状结构。

我一直在绞尽脑汁试图让这些要求正确。这或多或少是我所拥有的:

var request = require('request');


function scanPage(url) {

  // request the page at given url:


  request.get(url, function(err, res, body) {

    var pageObject = {};

    /* [... Jquery mumbo-jumbo to

        1. Fill the page object with information and
        2. Get the links on that page and store them into arrayOfLinks 

    */

    var arrayOfLinks = ['url1', 'url2', 'url3'];

    for (var i = 0; i < arrayOfLinks.length; i++) {

      pageObj[arrayOfLinks[i]] = scanPage[arrayOfLinks[i]];

    }
  });

    return pageObj;
}
Run Code Online (Sandbox Code Playgroud)

我知道这段代码在很多层面上都是错误的,但它应该让您了解我正在尝试做什么。

我应该如何修改它才能使其正常工作?(如果可能的话,不使用承诺)

(您可以假设该网站具有树状结构,因此每个页面仅具有指向三个页面下方页面的链接,因此采用递归方法)

javascript asynchronous node.js web-scraping

5
推荐指数
1
解决办法
1927
查看次数

当条件之一是承诺而另一个不是时,是否有惯用的方式在 JavaScript 中表达“if (c1 || c2)”?

当我仅在满足各种条件时才执行算法中的后续步骤时,我会这样表达:

if (sc1 || sc2) {
  do();
  various();
  things();
}
Run Code Online (Sandbox Code Playgroud)

当我仅根据承诺的履行执行后续步骤时,我可以这样表达:

asyncCheck().then(ac1 => {
  if (ac1) {
    do();
    various();
    things();
  }
}
Run Code Online (Sandbox Code Playgroud)

当条件sc1只是一个常规的旧同步表达式但条件ac2通过承诺异步出现时,我如何用惯用的 JavaScript表达?

假设原生 ES6 承诺和非平凡代码在满足条件时被执行。

例如,这种“明显”的方式看起来很丑陋:

if (sc1) {
  do();
  various();
  things();
} else {
  asyncCheck().then(ac2 => {
    if (ac2) {
      do();
      various();
      things();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我可以将重复的代码放在一个以任何方式调用的函数中,这样不那么难看,但我觉得我可能会遗漏一些其他 JavaScript 程序员可能正在使用的更惯用的东西。

我也应该添加这个观察:因为在我的情况下,有一个合乎逻辑的 or,它应该短路,所以如果简单检查已经是false.

javascript promise

5
推荐指数
1
解决办法
180
查看次数

Nodejs / Express中链接promise的最佳实践

我知道在Nodejs / Express中兑现承诺的最佳方法是:

doSomeThing()
.then()
.then()
.catch();
Run Code Online (Sandbox Code Playgroud)

但是最近不得不使用async和q模块来遍历列表/数组并运行async函数。我想知道这样做/编写此方法的更好方法-

var deferred = Q.defer();
var deferred2 = Q.defer();          
models.Local.findOne({
        where: {
            id: parseInt(req.body.localid)
        }
    })
    .then(function(resultLocal){
        if(!resultLocal){
            return res.status(404).json(
                {
                    "status" : "error",
                    'error': "Local Not Found"
                });
        }
        return models.Documents.create(req.body.document);
    })
    .then(function(docCreated){
            var attributes = req.body.document.Attributes;
            async.each(attributes, function(item, callback) {
                models.Doc_Tags.create({
                    value: item.value,
                    attribute_id: item.id,
                    document_id: docCreated.id
                })
                .then(function(attributeCreated){
                    var upObj = {};
                    upObj[item.col_name] = item.value;

                    models[item.table_name].update(upObj,{
                        where:{
                            id: req.body.document.local_id
                        }
                    })
                    .then(function(primaryUpdated){
                        deferred2.resolve();
                    })
                    .catch(function(error){
                        return res.status(400).json({status: 'error', error:error.message});
                    }); …
Run Code Online (Sandbox Code Playgroud)

javascript node.js promise express q

5
推荐指数
1
解决办法
1312
查看次数

ES6 Promise 错误未按预期冒泡

我从 E6 Promises 开始。我非常喜欢它们,但有一个关于错误处理的重要概念,我不明白,希望得到一些澄清。

让我们假设以下简单的函数返回一个承诺:

    function promiseString(str, timeout, doResolve) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (doResolve) {
                    resolve(str);
                } else {
                    reject(new Error("Rejecting " + str));
                }
            }, timeout);
        });
    }
Run Code Online (Sandbox Code Playgroud)

它非常简单,只为传递给它的字符串返回一个承诺,并导致该承诺在“超时”毫秒内被解析或拒绝(基于第三个参数)。

我可以按预期完全消耗它,如下所示:

            promiseString("One", 100, true)
                .then((str) => { console.log("First then is " + str); return promiseString(str + " two", 100, true); })
                .then((str) => { console.log("Second then is " + str); return promiseString(str + " three", 100, true); })
                .then((str) => console.log(str))
                .catch((err) => …
Run Code Online (Sandbox Code Playgroud)

javascript error-handling promise ecmascript-6

5
推荐指数
1
解决办法
2844
查看次数

返回一个承诺,如果找到一个值,则将其解析为布尔值true或false

我需要进行api调用,以返回ID和与其关联的值的响应。然后,promise解析并返回true或false(如果找到或未找到查询的id)。

我怎样才能做到这一点?使用诺言的新手。正如诺言似乎令人困惑

这是使用API​​的终点,UserService返回ID和薪水的数组。我需要检查ID是否存在以及薪水是否与查询匹配,然后Promise需要解析为true或false。

这是身份证和收入的对象

      [{
            "id": 1,
            "name": "Primary",
            "sal": [{
                    "id": "1",
                    "sal": "10"
                }, {
                    "id": "2",
                    "sal": "20"
                }]
            },{
            "id": 2,
            "name": "Secondary",
            "sal": [{
                    "id": "1",
                    "sal": "100"
                }, {
                    "id": "2",
                    "sal": "200"
                }
            ]
        }];


  UserService.hasUserValue(id, income).then(function(qualifiesforlowIncome){
     var isLowIncome = qualifiesforlowIncome
   }
Run Code Online (Sandbox Code Playgroud)

qualifyforlowIncome是返回true或false的布尔值。我正在使用角度,因此在这种情况下我应该执行$ q.defer并返回defer.promise吗?

对此还不太清楚

javascript promise angularjs angular-promise

5
推荐指数
1
解决办法
1万
查看次数

Javascript为承诺循环的每个项目运行异步代码

我有一个函数,它将一个对象传递给它,其中键和数据是一个数组.我必须调用API来获取附加信息,然后将其添加回对象并返回整个对象.

我的第一种方法是不正确的,因为我试图将数据传出.then(),但这是错误的做法.

function asignChecklistItems(taskArray) { 
    // get all the people's tasks passed in
    return new Promise(function(resolve, reject) {

        var promises = []

        // Task Array: {"Person":[tasks,tasks,tasks]}

        for (var person in taskArray) {
            var individualTaskPerson = taskArray[person]
            // get the person's tasks

            for (var individualTask in individualTaskPerson) {

                // here we get each individual task
                var task = individualTaskPerson[individualTask]

                // Check if the checklist is present, the .exists is a bool 
                if (task.checklist.exists === true) {
                //Here we push …
Run Code Online (Sandbox Code Playgroud)

javascript asynchronous node.js promise es6-promise

5
推荐指数
1
解决办法
205
查看次数

'await'即使在异步函数中也不起作用

我用谷歌搜索了这个,但找不到与我的问题有关的结果.我把'await'放在异步函数中但node.js说"SyntaxError:Unexpected identifier".有人可以帮忙吗?我刚刚开始学习JavaScript.

async function removeFile(data) {
    return new Promise((resolve, reject) => {
        try {
            if (!data.arg) {
                //check if there's filename
                data.msg.channel.send("What did you want me to remove baka?").then(async result => {
                    data.client.setTimeout(data.tsundere, 5000, result);
                });
            } else {
                //check if there's repo id in the config file (Personal)
                if (!data.config.group && !data.config.repo_id) {
                    data.msg.channel.send("Hmmph! Please set the repo channel ID in the config file first?");
                    //check if the channel is valid (Personal)
                } else if (!data.config.group && !data.msg.guild.channels.has(data.config.repo_id)) { …
Run Code Online (Sandbox Code Playgroud)

javascript promise async-await discord.js

5
推荐指数
1
解决办法
160
查看次数