最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何运行fibonacci函数异步?

运维笔记admin10浏览0评论

如何运行fibonacci函数异步?

如何运行fibonacci函数异步?

我学习node.js,我有异步斐波那契函数的问题。

书中的例子是没有ES6,但我在我的例子中使用了ES6。也许这是一个问题。

我的代码:

const http = require('http');
const url = require('url');

const fibonacciAsync = exports.fibonacciAsync = (n, done) => {
  if (n === 1 || n === 2) {
    done(1);
  } else {
    process.nextTick(() => {
      fibonacciAsync(n - 1, (val1) => {
        process.nextTick(() => {
          fibonacciAsync(n - 2, (val2) => {
            done(val1 + val2);
          })
        })
      })
    })
  }
}

http.createServer((req, res) => {
  const urlP = url.parse(req.url, true);
  let fibo;
  res.writeHead(200, {'Content-Type': 'text/plain'});
  if (urlP.query['n']) {
    fibo = fibonacciAsync(urlP.query['n']);
    res.end('Fibonacci ' + urlP.query['n'] + '=' + fibo);
  } 
}).listen(8124, '127.0.0.1');

这会返回错误:

TypeError:done不是“done(val1 + val2);”中的函数

回答如下:

你的脚本包含这一行:fibo = fibonacciAsync(urlP.query['n']);,它是对函数fibonacciAsync的调用。这些函数有两个参数:ndone(这是一个回调函数)。你对这个函数的调用只包含一个参数,即n参数,而done函数是undefined。所以当然,done不是function - 它是undefined

编辑:对于您的要求:我希望这对您有用。

http.createServer((req, res) => {
  const urlP = url.parse(req.url, true);
  let fibo;
  res.writeHead(200, {'Content-Type': 'text/plain'});
  if (urlP.query['n']) {
    fibonacciAsync(urlP.query['n'], function(data) {
        res.end('Fibonacci ' + urlP.query['n'] + '=' + data);
    });
  } 
}).listen(8124, '127.0.0.1');

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论