skip to Main Content

I try to load a text file with d3.text api as below, but it return a promise. I would expect it return the text file content.

async function loadSync(filename) {
    return await d3.text(filename)
}

function load_address() {
    var url = "https://example-files.online-convert.com/document/txt/example.txt"
    var addrs = loadSync(url)
    console.log(addrs)
}

load_address()
<script src="https://unpkg.com/[email protected]/dist/d3.min.js"></script>

2

Answers


  1. Probably you need to fetch the file first and then do the other things

    Login or Signup to reply.
  2. There are a couple of things going on here.

    First, you’re right that the result is a promise. Be sure to await within an async function at the appropriate time.

    Second, you’ll need to work around the Cross-origin policy issue with a CORS Proxy.

    async function load_address() {
        let proxy = 'https://corsproxy.io/?'
        var url = "https://example-files.online-convert.com/document/txt/example.txt"
        var addrs = await d3.text(proxy + url)
        console.log(addrs)
    }
    
    load_address()
    <script src="https://unpkg.com/[email protected]/dist/d3.min.js"></script>

    Of course, this is pretty easy to do with fetch as well:

    fetch("https://corsproxy.io/?https://example-files.online-convert.com/document/txt/example.txt").then(
      async function(r) {
      console.log(await r.text())
     }
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search