使用then()使函数在节点中按顺序运行 [英] use then() to make function run sequentially in node

查看:68
本文介绍了使用then()使函数在节点中按顺序运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在序列总线中运行循环函数该函数总是得到异步
有没有办法让它同步而不使用回调或任何外部库

i want to run loop function in sequence bus the function always gets async is there any way to make it sync without using callback or any external library

file 1

var db = require('./promiseUnderStanding');

var fun = function () {
    for (var i = 0; i < 10; i++) {
        db.getFromDb(i, 0);
    }
}
fun();

file2

var mysql = require("mysql");
module.exports = {
 getFromDb : function (num1,num2) {
    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'demo'
    });
    connection.connect();
    connection.query('SELECT '+num1+' + '+num2 +' AS solution', function (error, results, fields) {
        if (error) {
            console.log(err)
        }
        else {
            console.log('The solution is: ', results[0].solution);
        }
    })
    connection.end();
}

}


推荐答案

如果函数是异步的,这意味着它返回一个Promise。

If function is async, this means it returns a Promise.

const myFunc = function(){
    return new Promise(function(resolve, reject){
        if(failed){
            reject(dataSendToCatch);
        }if(!failed){
            resolve(dataSendToThen);
        }
    })
};

这几乎与以下相同:

const myFunc = async function(){
    if(failed) throw new Error();
        return dataSendToThen;
};

运行功能后,您可以链接异步甚至同步功能:

After running your function, you can chain async or even sync functions:

myFunc()
.then(function(dataFromResolve){return otherFunc()})
.then(function(dataFromOtherFunc){/*...*/});

对于连续处理,过滤,maping从异步函数接收的数据是好的 rxjs 库。

For continous handling, filtering, maping received data from async functions is good rxjs library.

这篇关于使用then()使函数在节点中按顺序运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆