第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

從fs.readFile獲取數(shù)據(jù)

從fs.readFile獲取數(shù)據(jù)

從fs.readFile獲取數(shù)據(jù)var content;fs.readFile('./Index.html', function read(err, data) {     if (err) {         throw err;     }     content = data;});console.log(content);原木undefined為什么?
查看完整描述

3 回答

?
慕的地6264312

TA貢獻(xiàn)1817條經(jīng)驗 獲得超6個贊

您定義的函數(shù)是一個異步回調(diào)。它不是立即執(zhí)行,而是在文件加載完成后執(zhí)行。調(diào)用readFile時,將立即返回控件,并執(zhí)行下一行代碼。因此,當(dāng)您調(diào)用控制臺日志時,您的回調(diào)尚未被調(diào)用,并且尚未設(shè)置此內(nèi)容。歡迎使用異步編程。

示例方法

const fs = require('fs');var content;// First I want to read the filefs.readFile('./Index.html', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;

    // Invoke the next step here however you like
    console.log(content);   // Put all of the code here (not the best solution)
    processFile();          // Or put the next step in a function and invoke it});function processFile() {
    console.log(content);}

或者更好的是,如Raynos示例所示,將調(diào)用包裝在一個函數(shù)中,并傳遞您自己的回調(diào)。(顯然,這是更好的實踐),我認(rèn)為,養(yǎng)成將異步調(diào)用包裝在函數(shù)中進(jìn)行回調(diào)的習(xí)慣,將為您節(jié)省大量的麻煩和混亂的代碼。

function doSomething (callback) {
    // any async callback invokes callback with response}doSomething (function doSomethingAfter(err, result) {
    // process the async result});


查看完整回答
反對 回復(fù) 2019-07-22
?
溫溫醬

TA貢獻(xiàn)1752條經(jīng)驗 獲得超4個贊

function readContent(callback) {
    fs.readFile("./Index.html", function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })}readContent(function (err, content) {
    console.log(content)})


查看完整回答
反對 回復(fù) 2019-07-22
  • 3 回答
  • 0 關(guān)注
  • 1341 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號